
import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/common/config/val_client_url_path.dart';
import 'package:valovault_reminder/common/ui/val_ui_kit_dialog_impl.dart';
import 'package:valovault_reminder/http/val_dio_fetch_kit.dart';
import 'package:valovault_reminder/pages/base/val_base_ui_page.dart';
import 'package:valovault_reminder/util/val_screen_size_kit.dart';
import 'package:valovault_reminder/util/val_toast_kit.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../common/util/val_app_state_tool.dart';
import '../../common/util/val_shared_preferences_tool.dart';
import '../base/val_app_common_bar.dart';

class ValMyHomeEditUserPage extends StatefulWidget {
  final String nickName;
  final String birthDate;
  final String userHeader;
  final String country;

  const ValMyHomeEditUserPage({super.key, this.nickName = '', this.birthDate = ''
    , this.userHeader = '', this.country = ''});

  @override
  State<ValMyHomeEditUserPage> createState() => _ValMyHomeEditUserPageState();
}

class _ValMyHomeEditUserPageState extends ValBaseUIPageState<ValMyHomeEditUserPage> {
  final TextEditingController controller = TextEditingController();
  final TextEditingController countryController = TextEditingController();
  final FocusNode fieldNode = FocusNode();
  final FocusNode countryFieldNode = FocusNode();

  String nickName = '';
  String birthDate = '';
  String country = '';
  bool showDateSheet = false;
  String editBirthDate = '';
  String headImagePath = '';
  DateTime startDate = DateTime.now().subtract(Duration(days: 18 * 365 + 4));//DateTime(DateTime.now().year - 18);
  String userHeaderUrl = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAppBar = true;
    bgColor = const Color(0xFF143A42);
    resizeToAvoidBottomInset = false;
    nickName = widget.nickName;
    birthDate = widget.birthDate;
    country = widget.country;
    controller.text = nickName;
    countryController.text = country;
    userHeaderUrl = widget.userHeader;
  }

  @override
  PreferredSizeWidget? get appBar {
    return ValAppCommonBar(
      backgroundColor: Colors.transparent,
      title: '',
      titleColor: Colors.white,
      brightness: Brightness.dark,
      leadingWidget: GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Image.asset(
            '${ValAssetsName.ASSETS_MINE}val_my_home_back_btn.png',
            width: 30,
            height: 30,
          )
      ),
    );
  }

  void postEditUserInfoData() {
    if (nickName.isEmpty) {
      ValToastKit.showMessage('nickName is empty');
      return;
    }
    if (birthDate.isEmpty) {
      ValToastKit.showMessage('birthDate is empty');
      return;
    }

    if (country.isEmpty) {
      ValToastKit.showMessage('country is empty');
      return;
    }

    ValUIKitDialogImpl.showProgress();
    ValDioFetchKit.getInstance().postJsonWithUrl(ValClientUrlPath.saveUserInfo, {'nickname': nickName, 'birthday': birthDate, 'country': country}, (data, errorCode, message){
      ValUIKitDialogImpl.hideProgress();
      Navigator.of(context).pop();
    }, (err){
      ValUIKitDialogImpl.hideProgress();
      ValToastKit.showMessage('Save Failed');
    });
  }
  
  void openOssPolicyView() {
    ValUIKitDialogImpl.showProgress();
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.ossPolicy, {}, (data, errorCode, message) {
      // CommonDialogImpl.hideProgress();
      if (errorCode == 0 && data != null) {
        uploadSelectedImageFile(data, headImagePath);
      }
    }, (err){
      ValUIKitDialogImpl.hideProgress();
      ValToastKit.showMessage('Save Failed');
    });
  }

  void uploadSelectedImageFile(Map<dynamic, dynamic> data, String path) async {
    DateTime dateTime = DateTime.now();
    String fileName = path.split('/').last;
    String format = fileName.split('.').last;
    int imageTimeName = dateTime.millisecondsSinceEpoch +
        (dateTime.microsecondsSinceEpoch ~/ 1000000);
    String imageName = '$imageTimeName.$format';
    String host = data!['host'];
    String dir = data!['dir'];
    var filePath = await MultipartFile.fromFile(path, filename: fileName);
    final formData = FormData.fromMap({
      'ossaccessKeyId': data!['accessKeyId'],
      'policy': data!['policy'],
      'signature': data!['signature'],
      'callback': data!['callback'],
      'key': '$dir/$imageName',
      'file': filePath,
    });

    ValDioFetchKit.getInstance().uploadFile(url: host, successCallBack: (data, errorCode, message) {
      if (errorCode == 0 && data != null) {
        String fileName = data["filename"];
        postUserHeadImage(fileName);
      }
    }, formData: formData, errorCallBack: (err){
      ValToastKit.showMessage('Upload Failed');
      ValUIKitDialogImpl.hideProgress();
    });
  }

  void postUserHeadImage(String filename) async {
    ValDioFetchKit.getInstance().postJsonWithUrl(ValClientUrlPath.updateAvatar, {"avatarPath": filename},
      (data, errorCode, message) {
        if (errorCode == 0 && data != null) {
          ValUIKitDialogImpl.hideProgress();
          ValToastKit.showMessage('Success');
          userHeaderUrl = data['mediaUrl'];
          saveUserHeadRecord();
          setState(() {});
        }
    }, (err) {
      ValUIKitDialogImpl.hideProgress();
      ValToastKit.showMessage('Edit Failed');
    });
  }

  void saveUserHeadRecord() async {
    String userId = ValAppStateTool().accountInfo?.userId ?? "userId";
    await ValLocalStore.saveValue("$userId-userHeader", userHeaderUrl);
  }

  void clickedDatePicker() {
    showModalBottomSheet(context: context,
      isDismissible: false,
      builder: (context) {
        return SizedBox(
          height: 400,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                height: 40,
                color: const Color(0xFFF5F5F5),
                padding: const EdgeInsets.only(left: 20, right: 20),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      onTap: (){
                        Navigator.pop(context);
                        setState(() {
                          editBirthDate = "";
                        });
                      },
                      child: Container(
                        margin: const EdgeInsets.only(right: 20,),
                        height: 28,
                        width: 60,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [
                              Color(0xFFE8A229),
                              Color(0xFFF9C03D),
                              Color(0xFFFCCC41),
                            ],
                          ),
                          borderRadius: BorderRadius.circular(24),
                        ),
                        child: const Text("Cancel",
                          style: TextStyle(color: Colors.black, fontSize: 14,),),
                      ),
                    ),
                    GestureDetector(
                      onTap: (){
                        Navigator.pop(context);
                        if (editBirthDate.isEmpty) {
                          editBirthDate = "${startDate.year}-${startDate.month}-${startDate.day}";
                        }
                        setState(() {
                          birthDate = editBirthDate;
                        });
                      },
                      child: Container(
                        height: 28,
                        width: 60,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [
                              Color(0xFFE8A229),
                              Color(0xFFF9C03D),
                              Color(0xFFFCCC41),
                            ],
                          ),
                          borderRadius: BorderRadius.circular(24),
                        ),
                        child: const Text("Yes",
                          style: TextStyle(color: Colors.black, fontSize: 14,),),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: CupertinoDatePicker(
                    mode: CupertinoDatePickerMode.date,
                    backgroundColor: Colors.white,
                    initialDateTime: startDate,
                    maximumDate: DateTime.now().subtract(Duration(days: 18 * 365 + 4)),
                    maximumYear: DateTime.now().year - 18,
                    minimumYear: DateTime.now().year - 200,
                    onDateTimeChanged: (sd) {
                      String dateValue = "${sd.year}-${sd.month}-${sd.day}";
                      setState(() {
                        editBirthDate = dateValue;
                      });
                    }),
              ),
            ],
          ));
      });
  }

  void clickedSendButtonEvent() {
    postEditUserInfoData();
  }

  void chooseImageFile() async {
    PermissionStatus value = await Permission.camera.request();
    if (value == PermissionStatus.permanentlyDenied) {
      ValToastKit.showMessage('You have not authorised this permission.');
      return;
    }
    final ImagePicker picker = ImagePicker();
    XFile? pickedFile = await picker.pickImage(source: ImageSource.camera);
    if (pickedFile == null) {
      return;
    }

    // setState(() {
      headImagePath = pickedFile!.path;
    // });
    openOssPolicyView();
  }

  void endKeyBoardEvent() {
    fieldNode.unfocus();

    setState(() {
      nickName = controller.text;
    });
  }

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        Positioned(
            top: 0, left: 0, right: 0, bottom: 0,
            child: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topRight,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFF143A42),
                      Color(0xFF090B24),
                    ],
                  ),))
        ),
        Positioned(
          top: 0, left: 0, right: 0, bottom: 0,
          child: Column(
            children: [
              //头像
              GestureDetector(
                onTap: chooseImageFile,
                child: Stack(
                  children: [
                    Container(
                      width: 101, height: 101,
                      margin: const EdgeInsets.only(top: 68, bottom: 30),
                      alignment: Alignment.bottomCenter,
                      clipBehavior: Clip.hardEdge,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                      ),
                      child: Image.network(userHeaderUrl, width: 101, height: 101, fit: BoxFit.fill,),
                      //headImagePath.isNotEmpty ? CircleAvatar(radius: 49, backgroundImage: FileImage(File(headImagePath))) : Image.asset('${CsConfig.ASSETS_MINE}mine_user_header.png', width: 98, height: 98,), //
                    ),
                    Positioned(
                      bottom: 30, right: 0,
                      child: Image.asset('${ValAssetsName.ASSETS_MINE}val_my_home_photo_btn.png', height: 30, width: 30,),
                    )
                  ],
                ),
              ),
              //昵称
              Container(
                height: 62,
                margin: const EdgeInsets.only(top:20, left: 30, bottom: 32, right: 30),
                padding: const EdgeInsets.only(left: 20, right: 20),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: Colors.white,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Expanded(
                      flex: 1,
                      child: Text('Nick Name', style: TextStyle(fontSize: 16, color: Color(0xFF999999)),)
                    ),
                    Expanded(
                      flex: 1,
                      child: TextField(
                        controller: controller,
                        textAlign: TextAlign.right,
                        focusNode: fieldNode,
                        style: const TextStyle(fontSize: 16, color: Color(0xFF404040)),
                        onTapOutside: (e) {
                          endKeyBoardEvent();
                        },
                        onEditingComplete: () {
                          endKeyBoardEvent();
                        },
                        decoration: const InputDecoration(
                          hintText: 'Enter your nick name',
                          hintStyle: TextStyle(fontSize: 16, color: Color(0xFF999999)),
                          isDense: true,
                          contentPadding: EdgeInsets.only(left: 16, top: 18, right: 10),
                          border: OutlineInputBorder(
                            gapPadding: 0,
                            borderSide: BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              //日期
              Container(
                height: 62,
                margin: const EdgeInsets.only(left: 30, bottom: 32, right: 30),
                padding: const EdgeInsets.only(left: 20, right: 20),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: Colors.white,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Expanded(
                        flex: 1,
                        child: Text('Date of Birth', style: TextStyle(fontSize: 16, color: Color(0xFF999999)),),
                    ),
                    Expanded(
                      flex: 1,
                      child: GestureDetector(
                        onTap: clickedDatePicker,
                        child: Text(birthDate, style: const TextStyle(fontSize: 16, color: Color(0xFF404040),), textAlign: TextAlign.right,)),
                    ),
                  ],
                ),
              ),
              //国家
              Container(
                height: 62,
                margin: const EdgeInsets.only(left: 30, bottom: 32, right: 30),
                padding: const EdgeInsets.only(left: 20, right: 20),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: Colors.white,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Expanded(
                        flex: 1,
                        child: Text('Country', style: TextStyle(fontSize: 16, color: Color(0xFF999999)),)
                    ),
                    Expanded(
                      flex: 1,
                      child: TextField(
                        controller: countryController,
                        textAlign: TextAlign.right,
                        focusNode: countryFieldNode,
                        style: const TextStyle(fontSize: 16, color: Color(0xFF404040)),
                        onTapOutside: (e) {
                          endKeyBoardEvent();
                        },
                        onEditingComplete: () {
                          endKeyBoardEvent();
                        },
                        decoration: const InputDecoration(
                          hintText: 'Enter country',
                          hintStyle: TextStyle(fontSize: 16, color: Color(0xFF999999)),
                          isDense: true,
                          contentPadding: EdgeInsets.only(left: 16, top: 18, right: 10),
                          border: OutlineInputBorder(
                            gapPadding: 0,
                            borderSide: BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              //发送按钮
              GestureDetector(
                onTap: clickedSendButtonEvent,
                child: Container(
                  margin: EdgeInsets.only(top: 44, bottom: 40 + ValScreenSizeKit.getBottomBarH(context)),
                  height: 49, width: 212,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                      colors: [
                        Color(0xFFE8A229),
                        Color(0xFFF9C03D),
                        Color(0xFFFCCC41),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(52),
                  ),
                  child: GestureDetector(
                    child: const Text("Publish",
                      style: TextStyle(color: Color(0xFF333333), fontSize: 20, fontWeight: FontWeight.w500),),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
